package com.ruoyi.dynamic.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.pojo.result.PageUtils;
import com.ruoyi.common.core.pojo.result.Pages;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.dynamic.mapper.GiftMapper;
import com.ruoyi.dynamic.model.constant.DynamicConstant;
import com.ruoyi.dynamic.model.pojo.entity.Gift;
import com.ruoyi.dynamic.model.pojo.request.app.AppGiftSearchRequest;
import com.ruoyi.dynamic.model.pojo.request.crm.CrmGiftAddOrEditRequest;
import com.ruoyi.dynamic.service.IGiftService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * <p>
 * 礼物表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-11-27
 */
@Service
public class GiftServiceImpl extends ServiceImpl<GiftMapper, Gift> implements IGiftService {


    @Override
    public Pages<Gift> listPage(AppGiftSearchRequest request, Long userId) {
        Page<Gift> giftPage = PageUtils.initPage(request, Gift.class);
        Page<Gift> page = lambdaQuery()
                .and(StringUtils.isNoneBlank(request.getSearch()),
                        wapper -> wapper.like(Gift::getGiftName, request.getSearch())
                ).orderByAsc(Gift::getGiftPrice)
                .page(giftPage);
        return PageUtils.pages(page);
    }

    @Override
    public Gift verify(Long id) {
        Optional<Gift> gift = lambdaQuery().eq(Gift::getId, id).oneOpt();
        Assert.isTrue(gift.isPresent(), "此礼物不存在");
        Gift one = gift.get();
        Assert.isTrue(one.getStatus().equals(DynamicConstant.CheckStatus.YES), "此礼物已下架");
        return one;
    }

    @Override
    public boolean addOrEdit(CrmGiftAddOrEditRequest request) {
        Gift one = getById(request.getId());
        if (CommonUtils.isNull(one)) {
            one = new Gift();
        }
        BeanUtils.copyProperties(request, one);
        return saveOrUpdate(one);
    }

    @Override
    public List<Gift> cutGift(Integer number, Set<Long> giftIds) {
        List<Gift> list = lambdaQuery()
                .eq(Gift::getStatus, DynamicConstant.CheckStatus.YES)
                .notIn(!giftIds.isEmpty(), Gift::getId, giftIds)
                .orderByAsc(Gift::getGiftPrice).last("limit 20")
                .list();
        Collections.shuffle(list);
        return list.subList(0, number);
    }
}
